<!-- 维修执行页面 -->
<template>
  <div class="repair-exec">
    <basic-container>
      <!-- <avue-form ref="badConfirmProperties" v-model="badCodeModel" :option="badCodeOption">
        <template slot="productSequenceNumber">
          <el-input ref="sequenceNumberProperties" placeholder="请输入产品序列号" v-model="badCodeModel.productSequenceNumber" @keyup.enter.native="submitBadCode" clearable>
          </el-input>
        </template>
        <template slot="packingSn">
          <el-input ref="packingSnProperties" placeholder="请输入包装条码" @keyup.enter.native="submitBadCode" v-model="badCodeModel.packingSn" clearable> </el-input>
        </template>
        <template slot="vehicleSn">
          <el-input ref="vehicleSnProperties" placeholder="请输入载具编码" @keyup.enter.native="submitBadCode" v-model="badCodeModel.vehicleSn" clearable> </el-input>
        </template>
      </avue-form> -->
      <avue-crud
        :option="option"
        :table-loading="loading"
        :search.sync="search"
        :data="data"
        :before-open="beforeOpen"
        v-model="form"
        ref="crud"
        :permission="permissionList"
        :row-class-name="tableRowClassName"
        @search-change="searchChange"
        @search-reset="searchReset"
        @selection-change="selectionChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
        @on-load="onLoad"
        @row-dblclick="rowDblclick"
      >
        <!-- <template slot="menuLeft">
          <div style="display: flex">
            <el-button type="primary" size="small" :disabled="ids.length > 0 ? false : true">维修开始</el-button>
            <el-button type="primary" size="small">维修结束</el-button>
          </div>
        </template> -->
        <!--        <template slot="menuRight">-->
        <!--          <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>-->
        <!--        </template>-->
        <template slot-scope="{ row, index }" slot="menu">
          <el-button icon="el-icon-view" size="mini" type="text" @click="viewDetail(index, row)">详情</el-button>
        </template>
        <template slot="productSequenceNumberSearch">
          <el-input name="productSequenceNumber" v-model="search.productSequenceNumber" placeholder="请输入产品序列号" @keyup.enter.native="selectionPush"></el-input>
        </template>
        <!-- <template slot="packingSnSearch">
          <el-input name="packingSn" v-model="search.packingSn" placeholder="请输入包装条码" @keyup.enter.native="selectionPackingSnPush"></el-input>
        </template> -->
        <!-- :disabled="disabledVehicleSn" -->
        <template slot="vehicleSnSearch">
          <el-input name="vehicleSn" v-model="search.vehicleSn" placeholder="请输入载具编码" @keyup.enter.native="selectionVehicleSnPush"></el-input>
        </template>
        <template slot="objectType" slot-scope="scope">
          <span v-if="scope.row.objectType == 'PRODUCT'">产品</span>
          <span v-if="scope.row.objectType == 'CARRIER'">载具</span>
        </template>
        <!-- <template slot="registrySourceForm">
          <span v-if="form.registrySource == 'AUTO'">自动</span>
          <span v-else-if="form.registrySource == 'MANUAL'">手动</span>
        </template> -->
      </avue-crud>
      <div class="btn-repair">
        <el-button type="primary" size="small" v-if="permission.repairExec_startRepair" @click="repairStart">维修开始</el-button>
        <el-button type="primary" size="small" v-if="permission.repairExec_endRepair" @click="getMrodictList">维修结束 </el-button>
        <!-- <el-button v-else type="primary" size="small" @click="repairSuccessVisible = true">维修完成</el-button> -->
      </div>
    </basic-container>

    <el-dialog class="dialog" append-to-body :close-on-click-modal="false" title="详情" :visible.sync="viewDialog" width="50%" top="20vh">
      <repairDetail :rowData="rowData" :isAuto="isAuto" :activeName="activeName">
        <table border="1" cellspacing="0" cellpadding="0" style="width: 100%">
          <tbody style="border: 1px solid #ebeef5">
            <tr style="height: 40px">
              <td class="tdStyle">序列号:</td>
              <td style="width: 300px">{{ rowData.productSequenceNumber }}</td>
              <td class="tdStyle">条码类型:</td>
              <td style="width: 300px" v-if="rowData.objectType == 'PRODUCT'">产品</td>
              <td style="width: 300px" v-else>载具</td>
            </tr>
            <tr style="height: 40px">
              <td class="tdStyle">产品数量:</td>
              <td>{{ rowData.quantity }}</td>
              <td class="tdStyle">不良来源:</td>
              <td>{{ rowData.registrySource }}</td>
            </tr>
            <tr style="height: 40px">
              <td class="tdStyle">当前所处工序:</td>
              <td>{{ rowData.currRouteName }}</td>
              <td class="tdStyle">不良产生工序:</td>
              <td>{{ rowData.fromRouteName }}</td>
            </tr>
            <tr style="height: 40px">
              <td class="tdStyle">不良代码:</td>
              <td>{{ rowData.failureCode }}</td>
              <td class="tdStyle">不良现象描述:</td>
              <td>{{ rowData.failureName }}</td>
            </tr>
            <tr style="height: 40px">
              <td class="tdStyle">不良登记人员:</td>
              <td>{{ rowData.confirmByName }}</td>
              <td class="tdStyle">不良登记时间:</td>
              <td>{{ rowData.registryDate }}</td>
            </tr>
            <tr style="height: 40px">
              <td class="tdStyle">不良原因大类:</td>
              <td style="width: 300px">{{ rowData.mainCauseName }}</td>
              <td class="tdStyle">不良原因小类:</td>
              <td style="width: 300px">{{ rowData.subCauseName }}</td>
            </tr>
            <tr style="height: 40px">
              <td class="tdStyle">不良确认人员:</td>
              <td style="width: 300px">{{ rowData.confirmByName }}</td>
              <td class="tdStyle">不良确认时间:</td>
              <td style="width: 300px">{{ rowData.confirmTime }}</td>
            </tr>
            <tr style="height: 40px">
              <td class="tdStyle">进维修时间:</td>
              <td style="width: 300px">{{ rowData.repairInTime }}</td>
              <td class="tdStyle">工单号:</td>
              <td>{{ rowData.workOrderNo }}</td>
            </tr>

            <tr style="height: 40px">
              <td class="tdStyle">车间:</td>
              <td style="width: 300px">{{ rowData.workshopName }}</td>
              <td class="tdStyle">产线:</td>
              <td style="width: 300px">{{ rowData.lineName }}</td>
            </tr>
            <tr style="height: 40px">
              <td class="tdStyle">产品名称:</td>
              <td style="width: 300px">{{ rowData.partName }}</td>
              <td class="tdStyle">产品编码:</td>
              <td style="width: 300px">{{ rowData.partNo }}</td>
            </tr>
            <tr style="height: 40px">
              <td class="tdStyle">产品型号:</td>
              <td style="width: 300px">{{ rowData.partModel }}</td>
            </tr>
          </tbody>
        </table>
      </repairDetail>
    </el-dialog>

    <el-dialog
      title="选择维修站"
      :visible.sync="dialogVisible"
      v-if="dialogVisible"
      width="25%"
      :modal-append-to-body="false"
      :show-close="true"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form ref="centerForm" :model="dialogForm" :rules="rules">
        <el-form-item label="车间" :label-width="formLabelWidth" prop="workshopId">
          <el-select v-model="dialogForm.workshopId" clearable placeholder="请选择" @change="getCenterList($event)">
            <el-option v-for="item in workshopList" :key="item.workshopId" :label="item.workshopName" :value="item.workshopId"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="维修站" :label-width="formLabelWidth" prop="centerId">
          <el-select v-model="dialogForm.centerId" clearable placeholder="请选择" @change="getCenterName">
            <el-option v-for="item in centerList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" icon="el-icon-check" @click="searchData">确 认</el-button>
        <el-button size="small" icon="el-icon-circle-close" @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>

    <el-dialog
      custom-class="repairExecDialog"
      title="选择维修代码"
      width="60%"
      :visible.sync="repairEndVisible"
      :modal-append-to-body="false"
      :append-to-body="true"
      :show-close="true"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @open="handleRepairOpen"
    >
      <el-form class="centerForm1" ref="centerForm1" :rules="repairEndFormRules" :model="repairEndForm" :label-width="formLabelWidth">
        <el-form-item class="inline" label="本次维修用时：">
          <el-input v-model="repairTime" :disabled="true" class="repair-time-input"> </el-input>
        </el-form-item>
        <el-form-item class="inline" label="位号：" prop="locationCode">
          <el-input type="text" placeholder="请输入位号" v-model="repairEndForm.locationCode" class="repair-time-input"> </el-input>
        </el-form-item>
        <el-form-item class="inline repairId" label="维修代码：">
          <el-select v-model="repairEndForm.repairId" multiple collapse-tags clearable filterable placeholder="请选择">
            <el-option v-for="item in serviceCodeList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="inline" label="是否需换料：">
          <el-radio-group v-model="repairEndForm.isReload">
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="维修备注：">
          <el-input
            type="textarea"
            placeholder="请输入维修备注"
            :autosize="{ minRows: 3, maxRows: 5 }"
            v-model="repairEndForm.remark"
            class="repair-time-input"
            maxlength="120"
            show-word-limit
          >
          </el-input>
        </el-form-item>
      </el-form>

      <!-- 换料物料列表 -->
      <avue-crud
        v-if="repairEndForm.isReload"
        ref="reloadCrud"
        v-model="reload.form"
        :option="reload.option"
        :data="reload.data"
        @row-update="handleReloadRowUpdate"
        @row-save="handleReloadRowSave"
        @row-del="handleReloadRowDel"
      >
      </avue-crud>

      <el-upload
        ref="fileUpload"
        class="upload-demo"
        drag
        multiple
        action="/api/blade-resource/oss/endpoint/put-file-attach"
        accept=".png,.jpg"
        list-type="picture"
        :headers="headersObj"
        :on-remove="removeFile"
        :on-success="pictureUploadSuccess"
        :before-upload="beforeUpload"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
      <!-- <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="fileUploadBox = false"><i class="el-icon-circle-close"></i><span>关 闭</span></el-button>
      </span> -->
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" icon="el-icon-check" @click="repairEnd">确 认</el-button>
        <el-button size="small" icon="el-icon-circle-close" @click="repairEndVisible = false">取 消</el-button>
      </span>
    </el-dialog>
    <ul class="repair-right">
      <li>维修人：{{ userName }}</li>
      <li>维修站：{{ centerName }}</li>
      <li v-if="repairEndVisible">本次维修时间：{{ repairTime }}</li>
      <li v-else>
        <el-button type="primary" size="mini" @click="dialogVisible = true">维修站设置</el-button>
      </li>
    </ul>
    <global-modal-template :visibile.sync="visibile" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </global-modal-template>
  </div>
</template>

<script>
import GlobalModalTemplate from '@/components/common-modal-template/global-modal-template.vue';
import repairDetail from '@/components/repair/detail.vue';
import { compressImg } from '@/util/compressImg';
import { getList, getDetail, repairStart, repairEnd, getCenterList, getMrodictList } from '@/api/repair/repairExec';
import { getWorkshopAndLine } from '@/api/repair/repairout';
import { focusInput } from '@/util/helpers';
import { timeDifference } from '@/util/util';
import website from '@/config/website';
import { getToken } from '@/util/auth';
import { mapGetters } from 'vuex';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
const validateLocationCode = (rule, value, callback) => {
  // let reg = /^[a-zA-Z0-9_]{0,}$/;
  let reg = /[\u4e00-\u9fa5]/;
  if (reg.test(value)) {
    callback(new Error('位号不能输入中文!'));
  } else {
    callback();
  }
};
export default {
  name: 'Repairexec',
  components: {
    GlobalModalTemplate,
    repairDetail,
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'REPAIR_EXEC',
      isAuto: false,
      activeName: 'first',
      visibile: false,
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      rowData: {},
      viewDialog: false,
      fileUploadBox: false,
      form: {
        workshopId: '',
        lineId: ''
      },
      query: {},
      fileList: [],
      returnObject: {},
      search: {
        productSequenceNumber: null
      },
      loading: true,
      selectionList: [],
      // 报废产品列表
      scopeProdList: [],

      option: {
        header: true,
        height: 'calc(100vh - 440px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 12,
        searchMenuPosition: 'right',
        border: true,
        index: true,
        indexLabel: '序号',
        selection: false,
        dialogClickModal: false,
        searchLabelWidth: 120,
        labelWidth: 120,
        searchSpan: 6,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        searchBtn: false,
        emptyBtn: false,
        viewBtn: false,
        menuWidth: 100,
        selectable: (row, index) => {
          // 表格禁用
          if (this.disabledProductSequence) {
            return false;
          } else {
            return true;
          }
        },
        columnBtn: false,
        column: [
          {
            label: '序列号',
            prop: 'productSequenceNumber',
            search: true,
            searchSpan: 8,
            searchOrder: 2,
            searchLabelWidth: 100,
            minWidth: 100,
            searchRules: [
              {
                required: false,
                message: '请输入产品序列号',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '载具编码',
            prop: 'vehicleSn',
            hide: true,
            viewDisplay: false,
            search: true,
            searchSpan: 8,
            searchOrder: 2,
            searchLabelWidth: 100,
            minWidth: 100
          },
          {
            label: '工单号',
            order: 16,
            prop: 'workOrderNo'
          },
          {
            label: '条码类型',
            prop: 'objectType',
            order: 2,
            viewDisplay: true,
            searchLabelWidth: 100,
            searchSpan: 6,
            search: true,
            searchOrder: 1,
            type: 'select',
            value: 'PRODUCT',
            searchValue: 'PRODUCT',
            dicData: [
              {
                label: '产品序列号',
                value: 'PRODUCT'
              },
              {
                label: '载具',
                value: 'CARRIER'
              }
            ],
            control: (val, form) => {
              if (form.objectType == 'PRODUCT') {
                return {
                  productSequenceNumber: {
                    display: true
                  },
                  vehicleSn: {
                    display: false
                  }
                };
              } else if (form.objectType == 'CARRIER') {
                return {
                  productSequenceNumber: {
                    display: false
                  },
                  vehicleSn: {
                    display: true
                  }
                };
              }
            },
            change: ({ value }) => {
              if (value == 'PRODUCT') {
                // this.search.packingSn = '';
                this.search.vehicleSn = '';
              }
              // else if (value == 'PACKING') {
              //   this.search.productSequenceNumber = '';
              //   this.search.vehicleSn = '';
              // }
              else if (value == 'CARRIER') {
                // this.search.packingSn = '';
                this.search.productSequenceNumber = '';
              }
            },
            searchRules: [
              {
                required: true,
                message: '请选择条码类型',
                trigger: 'change'
              }
            ]
          },
          {
            label: '产品数量',
            prop: 'quantity',
            order: 3,
            viewDisplay: true
          },
          {
            label: '当前所处工序',
            prop: 'currRouteName',
            order: 5,
            viewDisplay: true
          },
          {
            label: '不良产生工序',
            prop: 'fromRouteName',
            order: 6
          },
          {
            label: '不良来源',
            prop: 'registrySource',
            type: 'select',
            hide: true,
            order: 4,
            dicData: [
              {
                label: '自动',
                value: 'AUTO'
              },
              {
                label: '手动',
                value: 'MANUAL'
              }
            ]
          },
          {
            label: '不良代码',
            order: 7,
            span: 24,
            prop: 'failureCode'
          },
          {
            label: '不良登记人员',
            minWidth: 120,
            order: 9,
            prop: 'registryByName',
            hide: true
          },
          {
            label: '不良登记时间',
            prop: 'registryDate',
            order: 10,
            hide: true,
            type: 'datetime'
          },
          {
            label: '不良现象描述',
            prop: 'failureName',
            span: 24,
            minWidth: 120,
            order: 8,
            type: 'textarea',
            minRows: 3,
            maxRows: 3,
            row: true
          },
          {
            label: '车间',
            prop: 'workshopName',
            hide: true,
            order: 17,
            type: 'select'
          },
          {
            label: '产线',
            prop: 'lineName',
            hide: true,
            order: 18,
            type: 'select'
          },
          {
            label: '产品编码',
            order: 20,
            prop: 'partNo'
          },
          {
            label: '产品名称',
            order: 19,
            prop: 'partName'
          },
          {
            label: '产品型号',
            order: 21,
            hide: true,
            prop: 'partModel'
          },
          {
            label: '不良原因大类',
            minWidth: 120,
            order: 11,
            prop: 'mainCauseName',
            hide: true
          },
          {
            label: '不良原因小类',
            minWidth: 120,
            order: 12,
            prop: 'subCauseName',
            hide: true
          },
          {
            label: '不良确认人员',
            minWidth: 120,
            order: 13,
            prop: 'confirmByName',
            hide: true
          },
          {
            label: '不良确认时间',
            minWidth: 120,
            prop: 'confirmTime',
            type: 'datetime',
            order: 14,
            hide: true
          },
          {
            label: '进维修时间',
            minWidth: 120,
            prop: 'repairInTime',
            type: 'datetime',
            order: 15,
            hide: true
          }
        ]
      },
      // repairEndFormOption: {
      //   submitBtn: false,
      //   emptyBtn: false,
      //   column: [
      //     {
      //       label: '维修代码',
      //       minWidth: 120,
      //       prop: 'repairId',
      //       type: 'select',
      //     }
      //   ]
      // },
      data: [],
      dialogVisible: false,
      dialogForm: {
        workshopId: null,
        centerId: undefined,
        // 数据状态，不良确认：1，待维修：2，进维修：6，维修中：7，维修结束：8，出维修：9
        statusStr: '6,7'
      },
      // 车间列表
      workshopList: [],
      formLabelWidth: '120px',
      rules: {
        centerId: [{ required: true, message: '请选择维修站', trigger: 'change' }],
        workshopId: [{ required: true, message: '请选择车间', trigger: 'change' }]
      },
      rulesSuccessForm: {
        scrapReason: [{ required: true, message: '请输入报废原因', trigger: 'blur' }]
      },
      // 维修站列表
      centerList: [],
      centerName: '***',
      repairEndVisible: false,
      repairEndForm: {
        repairId: null,
        isReload: 0,
        locationCode: ''
      },
      repairEndFormRules: {
        locationCode: [{ validator: validateLocationCode, trigger: 'blur' }]
      },
      // 维修代码列表
      serviceCodeList: [],
      // 是否禁止产品序列号和产品列表禁用
      disabledProductSequence: false,
      // 是否禁止载具禁用
      disabledVehicleSn: false,
      // 维修是否结束
      isRepairEnd: false,
      // 维修所用时间
      repairTime: '',
      // 开始维修时间
      startRepairTime: '',
      selectionLength: 1,
      userName: '***',
      isComputed: false,
      reload: {
        form: {},
        option: {
          columnBtn: false,
          refreshBtn: false,
          addBtn: true,
          labelWidth: 130,
          menuWidth: 200,
          maxHeight: 300,
          column: [
            {
              label: '维修序列号',
              prop: 'productSequenceNumber',
              type: 'select',
              dicData: [],
              span: 24,
              value: '',
              filterable: true,
              rules: [
                {
                  required: true,
                  message: '请选择维修序列号',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: '物料编码',
              prop: 'newPartNo',
              searchType: 'input',
              type: 'search',
              disabled: true,
              span: 24,
              placeholder: '请选择 物料编码',
              rules: [
                {
                  required: false,
                  message: '请输入物料编码',
                  trigger: 'blur'
                }
              ],
              appendClick: () => {
                this.openUserCommonModal({ type: 'productCode' });
              }
            },
            {
              label: '物料名称',
              prop: 'newPartName',
              span: 24,
              disabled: true,
              rules: [
                {
                  required: false,
                  message: '请输入物料名称',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: '维修使用数量',
              prop: 'quantity',
              span: 24,
              rules: [
                {
                  required: true,
                  trigger: 'blur',
                  validator: (rule, value, callback) => {
                    let reg = /^[1-9]\d*$/g;
                    if (value) {
                      if (!reg.test(value)) {
                        callback(new Error('物料维修使用数量不能小于等于0并且是整数！'));
                      } else {
                        callback();
                      }
                    } else {
                      callback('请输入物料维修使用数量');
                    }
                  }
                }
              ]
            },
            {
              label: '位号',
              prop: 'trackNo',
              span: 24,
              rules: [
                {
                  validator: validateLocationCode,
                  required: true,
                  trigger: 'blur'
                }
              ]
            }
          ]
        },
        data: []
      }
    };
  },
  computed: {
    ...mapGetters(['permission']),
    headersObj() {
      let header = { Authorization: `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}` };
      header['Blade-Auth'] = 'bearer ' + getToken();
      return header;
    },
    permissionList() {
      return {
        viewBtn: this.vaildData(this.permission.repairExec_view, false)
      };
    },
    ids() {
      let ids = [];
      this.isComputed = false;
      let scopeProdList = JSON.parse(JSON.stringify(this.scopeProdList));
      scopeProdList.forEach((ele) => {
        // 不等于7（维修中）的才可以维修开始
        if (ele.status !== 7) {
          ids.push(ele.id);
        }
      });
      return ids;
    },
    repairProgressIds() {
      let ids = [];
      let scopeProdList = JSON.parse(JSON.stringify(this.scopeProdList));
      scopeProdList.forEach((ele) => {
        // 等于7（维修中）的才可以维修结束
        if (ele.status === 7) {
          ids.push(ele.id);
        }
      });
      return ids;
    },
    repairProgressData() {
      let ids = [];
      let scopeProdList = JSON.parse(JSON.stringify(this.scopeProdList));
      scopeProdList.forEach((ele) => {
        // 等于7（维修中）的才可以维修结束
        if (ele.status === 7) {
          ids.push({
            value: ele.id,
            label: ele.productSequenceNumber
          });
        }
      });
      return ids;
    }
  },
  watch: {
    'dialogForm.workshopId'(val) {
      getCenterList({ workshopId: val }).then((res) => {
        this.centerList = res.data.data;
        this.centerList.find((item) => {
          if (item.id === this.dialogForm.centerId) {
            this.centerName = item.name;
          }
        });
      });
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
    this.serviceCodeList = [];
    // 获取车间列表及产线接口
    this.getWorkShopList();

    const userInfo = JSON.parse(localStorage.getItem('saber-userInfo'));
    if (userInfo && userInfo.content.user_name) {
      this.userName = userInfo.content.user_name;
    }
    if (localStorage.getItem('start-repair-time')) {
      this.startRepairTime = localStorage.getItem('start-repair-time');
    }
    this.$store.commit('GET_REPAIR_STATION');
    this.dialogForm.workshopId = this.$store.state.repair.repairStation.workshopId;
    this.dialogForm.centerId = this.$store.state.repair.repairStation.centerId;

    if (!this.dialogForm.workshopId || !this.dialogForm.centerId) {
      this.dialogVisible = true;
    }
    if (this.dialogForm.workshopId && this.dialogForm.centerId) {
      this.onLoad();
    }
    // this.$store
    // 新增处理--加一个车间，维修站的缓存
    // if (sessionStorage.getItem('workshopId')) {
    //   this.dialogForm.workshopId = sessionStorage.getItem('workshopId');
    //   this.getCenterList(this.dialogForm.workshopId);
    // }
    // const centerObj = JSON.parse(sessionStorage.getItem('centerObj'));
    // if (centerObj) {
    //   this.dialogForm.centerId = centerObj.id;
    //   this.centerName = centerObj.name;
    //   this.onLoad();
    // }
    // 默认打开页面弹层,tab页签切换时候，直接赋值或用$nextTick会出现闪屏
    // setTimeout(() => {
    //   if (!centerObj) {
    //     this.dialogVisible = true;
    //   }
    // }, 200);
  },
  methods: {
    removeFile(file) {
      this._forEach(this.fileList, (item, index) => {
        if (item.link === file.response.data.link) {
          this.fileList.splice(index, 1);
        }
      });
      this.returnObject['attachmentUrls'] = JSON.stringify(this.fileList);
    },
    pictureUploadSuccess(res) {
      this.fileList.push({
        attachmentId: res.data.attachId,
        link: res.data.link
      });
      this.returnObject['attachmentUrls'] = JSON.stringify(this.fileList);
    },
    beforeUpload(file) {
      return new Promise(async (resolve, reject) => {
        if (!file.type.includes('image')) {
          this.$message.warning('请上传图片');
          reject(new Error('请上传图片'));
          return;
        }
        if (file.type != 'image/png' && file.type != 'image/jpeg') {
          this.$message.warning('请上传正确的文件类型！');
          reject(new Error('请上传正确的文件类型！'));
          return;
        }
        try {
          const newFile = await compressImg(file);
          resolve(newFile);
        } catch (e) {
          console.log(e);
        }
      });
      //图片压缩
      // if (Number(file.size / 1024) > 200) {
      //   this.$message({
      //     type: 'warning',
      //     message: '上传的文件大小超出限制！'
      //   });
      //   return false;
      // }
    },
    rowDblclick(row) {
      if (this.scopeProdList.length > 0) {
        let findIndex = this.scopeProdList.findIndex((item) => item.id === row.id);
        if (findIndex > -1) {
          this.scopeProdList.splice(findIndex, 1);
        }
      }
    },
    // 获取维修站列表
    getCenterList(val) {
      // if (val) {
      //   sessionStorage.setItem('workshopId', val);
      // }
      this.$store.commit('SET_REPAIR_STATION', this.dialogForm);

      getCenterList({ workshopId: val }).then((res) => {
        this.centerList = res.data.data;
        this.dialogForm.centerId = '';
        // const centerObj = JSON.parse(sessionStorage.getItem('centerObj'));
        // if (centerObj && sessionStorage.getItem('workshopId') === val) {
        //   this.dialogForm.centerId = centerObj.id;
        // }
      });
    },
    // 产品序列号扫描自动加入
    selectionPush() {
      const selectData = this.data.find((item) => item.productSequenceNumber === this.search.productSequenceNumber && this.search.objectType == item.objectType);
      if (selectData) {
        this.scopeProdList.push(selectData);
      } else {
        this.$message({
          type: 'warning',
          message: '请输入正确的序列号！'
        });
      }
      this.search.productSequenceNumber = '';
    },
    // 包装条码扫描自动加入
    // selectionPackingSnPush() {
    //   const selectData = this.data.find((item) => item.productSequenceNumber === this.search.packingSn && this.search.objectType == item.objectType);
    //   if (selectData) {
    //     this.scopeProdList.push(selectData);
    //   } else {
    //     this.$message({
    //       type: 'warning',
    //       message: '请输入正确的包装条码！'
    //     });
    //   }
    //   this.search.packingSn = '';
    // },
    // 载具扫描自动加入
    selectionVehicleSnPush() {
      const selectData = this.data.find((item) => item.productSequenceNumber === this.search.vehicleSn && this.search.objectType == item.objectType);
      if (selectData) {
        this.scopeProdList.push(selectData);
      } else {
        this.$message({
          type: 'warning',
          message: '请输入正确的载具编码！'
        });
      }
      this.search.vehicleSn = '';
    },
    getCenterName(val) {
      this.$store.commit('SET_REPAIR_STATION', this.dialogForm);
      // this.centerList.find((item) => {
      //   if (item.id === val) {
      //     this.centerName = item.name;
      //     sessionStorage.setItem('centerObj', JSON.stringify({ id: item.id, name: item.name }));
      //   }
      // });
    },
    // 获取车间列表及产线接口
    getWorkShopList() {
      getWorkshopAndLine().then((res) => {
        this.workshopList = res.data.data;
      });
    },
    // 获取维修代码列表接口
    getMrodictList() {
      this.repairEndVisible = true;
      // 只在第一次打开弹窗调取接口，后续不请求，如数据变动请重新进入。
      if (this.serviceCodeList.length < 1) {
        getMrodictList({ dictType: 'ACTION' }).then((res) => {
          res.data.data.map((d) => {
            d.id = String(d.id);
          });
          this.serviceCodeList = res.data.data;
        });
      }
      if (!this.startRepairTime) {
        this.startRepairTime = new Date();
      }
      const time = new Date();
      this.repairTime = timeDifference(this.startRepairTime, new Date());
    },
    // 样式调整
    tableRowClassName({ row, rowIndex }) {
      const findData = this.scopeProdList.length > 0 ? this.scopeProdList.find((item) => item.productSequenceNumber === row.productSequenceNumber) : 0;
      if (findData) {
        return 'repair-select-row';
      }
      return '';
    },
    // 开始维修
    repairStart() {
      this.disabledProductSequence = true;
      // repairStart(this.ids).then((res) => {
      //   if (res.data.code === 200) {
      //     this.$message({
      //       type: 'success',
      //       message: res.data.msg
      //     });
      //     this.isComputed = true;
      //     this.refreshChange();
      //     this.startRepairTime = new Date();
      //     localStorage.setItem('start-repair-time', this.startRepairTime);
      //     // 禁用
      //     this.disabledProductSequence = true;
      //   }
      // });
    },
    // 结束维修
    repairEnd() {
      if (!this.repairEndForm.repairId) {
        this.$message({
          type: 'warning',
          message: '请选择维修代码后操作！'
        });
        return;
      }
      if (this.repairEndForm.isReload === 1) {
        if (this.reload.data.length == 0) {
          this.$message.warning('请输入换料数据');
          return;
        }
      }
      this.reload.data.forEach((d) => {
        let centerProductId = d.productSequenceNumber;
        d.centerProductId = centerProductId;
        let productSequenceNumber = this.repairProgressData.find((prog) => prog.value == d.productSequenceNumber);
        if (productSequenceNumber) {
          d.productSequenceNumber = productSequenceNumber.label;
        }
      });

      this.$refs['centerForm1'].validate((valid) => {
        if (valid) {
          let productHandlingResultList = this.serviceCodeList
            .filter((code) => this.repairEndForm.repairId.includes(code.id))
            .map((c) => {
              return {
                resultId: c.id,
                resultCode: c.code,
                resultName: c.name
              };
            });
          let params = {
            idArray: this.repairProgressIds,
            imageList: this.fileList,
            locationCode: this.repairEndForm.locationCode,
            productHandlingResultList: productHandlingResultList,
            remark: this.repairEndForm.remark,
            refuelingVOList: this.repairEndForm.isReload ? this.reload.data : []
          };
          console.log(params, '结束维修提交参数');
          repairEnd(params).then((res) => {
            if (res.data.code === 200) {
              this.$message({
                type: 'success',
                message: res.data.msg
              });
              this.selectionLength = this.scopeProdList.length;
              this.scopeProdList = [];
              this.refreshChange();
              this.repairEndVisible = false;
              // this.isRepairEnd = true
              this.repairTime = res.data.data;
              // this.option.column[1].search = true
              localStorage.setItem('repair-time', res.data.data);
              // 禁用
              this.disabledProductSequence = false;
              this.disabledVehicleSn = false;
            }
          });
        } else {
          return false;
        }
      });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad();
    },
    searchChange(params, done) {
      if (params.receiveDate && params.receiveDate.length > 0) {
        params.startTime = params.receiveDate[0];
        params.endTime = this.$moment(this.$moment(params.receiveDate[1]).add(1, 'days')).format('YYYY-MM-DD');
        delete params.receiveDate;
      }
      // this.query = params;
      this.onLoad();
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {},
    sizeChange(pageSize) {},
    refreshChange() {
      this.onLoad();
    },
    searchData() {
      this.$refs.centerForm.validate(async (valid) => {
        if (valid) {
          // 做数据临时存储
          this.centerList.find((item) => {
            if (item.id === this.dialogForm.centerId) {
              this.centerName = item.name;
              // sessionStorage.setItem('centerObj', JSON.stringify({ id: item.id, name: item.name }));
            }
          });
          // sessionStorage.setItem('workshopId', this.dialogForm.workshopId);
          await this.onLoad();
          this.dialogVisible = false;
          this.$nextTick(() => {
            focusInput('productSequenceNumber');
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    onLoad(page, params = {}) {
      if (this.dialogForm.centerId) {
        this.loading = true;
        getList(Object.assign(params, this.query, this.dialogForm)).then((res) => {
          const data = res.data.data;

          this.data = data;
          this.loading = false;
          this.selectionClear();

          this.$nextTick(() => {
            this.data.forEach((row) => {
              // 状态为维修中默认选中
              if (row.status === 7) {
                var findObj = this.scopeProdList.length > 0 ? this.scopeProdList.findIndex((item) => item.id === row.id) : -1;

                if (findObj === -1) {
                  this.scopeProdList.push(row);
                } else {
                  this.scopeProdList.splice(findObj, 1, row);
                }
                // 开启禁用状态
                if (row.objectType == 'CARRIER') {
                  this.disabledVehicleSn = true;
                } else {
                  this.disabledProductSequence = true;
                }
              } else if (row.status === 8) {
                // 维修结束处理
                // this.disabledProductSequence = true
                // this.isRepairEnd = true
                // this.option.column[1].search = true
                // if (localStorage.getItem('repair-time')) {
                //     this.repairTime = localStorage.getItem('repair-time')
                // }
              }
            });
          });
        });
      } else {
        this.loading = false;
      }
    },
    viewDetail(idx, row) {
      this.isAuto = row.registrySource == 'AUTO';
      this.rowData = structuredClone(row);
      this.activeName = 'first';
      this.viewDialog = true;
    },
    openUserCommonModal(params) {
      let { type } = params;
      switch (type) {
        // 产品编码
        case 'productCode':
          this.modalName = 'partmasterModal';
          this.visibile = true;
          this.tableOption = {
            templateName: 'NOWORKPARTMASTER',
            url: '/api/mes-admin/part-master/page',
            isPage: true,
            url: '/api/mes-admin/part-master/page',
            modalTitle: '选择产品信息（双击进行选择）',
            rowSelectionType: 'single',
            menu: false,
            editBtn: false,
            menuWidth: 100,
            searchLabelWidth: 90
          };
          break;
        default:
          break;
      }
    },
    // 获取选择的物料模态框行数据
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'partmasterModal':
          this.reload.form.newPartName = this._get(rowData, 'name', '');
          this.reload.form.partMasterId = this._get(rowData, 'id', '');
          this.reload.form.newPartNo = this._get(rowData, 'partNo', '');
          break;
        default:
          break;
      }
    },
    handleRepairOpen() {
      let productSequenceNumberIndex = this.reload.option.column.findIndex((col) => col.prop == 'productSequenceNumber');
      // 多选
      if (this.repairProgressIds && this.repairProgressIds.length > 1) {
        this.reload.option.column[productSequenceNumberIndex].dicData = this.repairProgressData;
        this.reload.option.column[productSequenceNumberIndex].value = '';
      } else {
        // 单选
        this.$set(this.reload.option.column[productSequenceNumberIndex], 'dicData', this.repairProgressData);
        this.$set(this.reload.option.column[productSequenceNumberIndex], 'value', this.repairProgressData[0].value);
      }
    },
    handleReloadRowSave(form, done) {
      this.reload.data.push(form);
      done();
    },
    handleReloadRowUpdate(form, index, done, loading) {
      this.reload.data.splice(index, 1, form);
      done();
    },
    handleReloadRowDel(row, index) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.reload.data.splice(index, 1);
        })
        .then(() => {
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    // 重新加载公用表格弹窗组件
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .repair-select-row {
  background: #caf982 !important;
}
.repair {
  position: relative;
}
.repair-right {
  position: absolute;
  right: 60px;
  top: 82px;
  li {
    font-size: 14px;
    height: 20px;
  }
}
li {
  list-style: none;
}
.btn-repair {
  display: flex;
  margin: 15px;
  justify-content: flex-end;
}

.repair-time-input {
  position: relative;
  width: 100%;
}

@media screen and (max-width: 980px) {
  .repair-right {
    top: 10px;
  }
}

.tdStyle {
  background: #fafafa;
  font-weight: 700;
  color: #909399;
  text-align: right;
  width: auto;
  padding-right: 20px;
  white-space: nowrap;
}

td {
  padding: 5px;
  border: 1px solid #ebeef5;
}

.repairExecDialog {
  .centerForm1 {
    ::v-deep .el-form-item__label {
      line-height: 40px !important;
    }
    .inline {
      width: 50%;
      display: inline-block;
      &.repairId {
        .el-select {
          width: 100%;
        }
      }
    }
  }
}
</style>
